package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.pojo.User;
import com.jt.service.DubboCartService;
import com.jt.util.UserThreadLocal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {

    @Reference(check = false)
    private DubboCartService cartService;

    /**
     * 购物车数据展现
     * @param model
     * @return
     */
    @RequestMapping("/show")
    public String show(Model model, HttpServletRequest request){
        User user = (User) request.getAttribute("JT_USER");
        Long userId=user.getId();
        List<Cart> cartList = cartService.findCartListByUserId(userId);
        model.addAttribute("cartList",cartList);
        return "cart";
    }

    /**
     * 购物车数量修改
     */
    @RequestMapping("/update/num/{itemId}/{num}")
    @ResponseBody//1.以json形式返回； 2.表示ajax请求结束
    public void updateNum(Cart cart){//restful参数的名称和对象的属性名称一致，可以使用对象方式接收
        Long userId= UserThreadLocal.getUser().getId();
        cart.setUserId(userId);
        cartService.updateCartNum(cart);
    }

    /**
     * 购物车删除操作
     */
    @RequestMapping("/delete/{itemId}")
    public String deleteCart(Cart cart){
        Long userId=UserThreadLocal.getUser().getId();
        cart.setUserId(userId);
        cartService.deleteCart(cart);
        return "redirect:/cart/show.html";
    }

    /**
     * 购物车添加操作
     */
    @RequestMapping("/add/{itemId}")
    public String addCart(Cart cart){
        Long userId=UserThreadLocal.getUser().getId();
        cart.setUserId(userId);
        cartService.addCart(cart);
        return "redirect:/cart/show.html";
    }
}
